import Router from 'koa-router'
import { isNil, cloneDeep } from 'lodash-es'
import { promisePool } from '../database/mysql2/index.js'

export const router = new Router()

// 扁平数组转树形结构
const buildTree = (data, parentCode = '') => {
  const tree = []
  data.forEach((node) => {
    if (node.parentCode === parentCode) {
      const children = buildTree(data, node.code)
      if (children.length) node.children = children
      tree.push(node)
    }
  })
  return tree
}

const getDataAndReSort = (dataList, code, sort) => {
  // 找到对应的同级数据并排序
  const getDataAndSort = (data, code) => {
    for (const item of data) {
      if (item.code === code) {
        item.sort = sort - 0.1
        return data.sort((a, b) => a.sort - b.sort)
      }
      if (item.children && item.children.length) {
        const result = getDataAndSort(item.children, code)
        if (result) return result
      }
    }
  }
  dataList = buildTree([...dataList])
  dataList = getDataAndSort(dataList, code)
  // 根据新sort再重新计算排序
  if (dataList.length) dataList[0].sort = Math.round(dataList[0].sort)
  for (let i = 1, len = dataList.length; i < len; i++) {
    dataList[i].sort = Math.round(dataList[i].sort)
    if (dataList[i - 1].sort >= dataList[i].sort) {
      dataList[i].sort = dataList[i - 1].sort + 1
    }
  }
  return dataList
}
// 新增与更新前的检查
// 检查name是否重复、code是否重复、parentCode是否存在
const updateBeforeInspect = async (body, ctx) => {
  // 新增时检查name是否重复、code是否重复、parentCode是否存在
  const [nameRows] = await promisePool.query(
    `SELECT * FROM data_dict WHERE name='${body.name}' AND id!='${body.id}'`
  )
  if (nameRows.length) {
    ctx.body = {
      code: 400,
      msg: '字典名称重复！'
    }
    return true
  }
  const [codeRows] = await promisePool.query(
    `SELECT * FROM data_dict WHERE code='${body.code}' AND id!='${body.id}'`
  )
  if (codeRows.length) {
    ctx.body = {
      code: 400,
      msg: '字典编码重复！'
    }
    return true
  }
  if (body.parentCode) {
    const [parentCodeRows] = await promisePool.query(
      `SELECT * FROM data_dict WHERE code='${body.parentCode}'`
    )
    if (!parentCodeRows.length) {
      ctx.body = {
        code: 400,
        msg: '父字典编码不存在！'
      }
      return true
    }
  }
}
// 新增字典数据
router.post('/api/v1/dict/types', async function (ctx) {
  const body = ctx.request.body
  if (await updateBeforeInspect(body, ctx)) return
  // 先插入一条数据再排序
  await promisePool.execute(
    `INSERT INTO data_dict (name,code,parentCode,status,sort,remark) values("${
      body.name
    }","${body.code}","${body.parentCode || ''}",${body.status},${body.sort},"${
      body.remark || ''
    }")`
  )
  const [rowList] = await promisePool.query(`SELECT * FROM data_dict`)
  const dataList = getDataAndReSort(rowList, body.code, body.sort)
  // console.log('dataList', dataList)
  for (const item of dataList) {
    await promisePool.execute(
      `UPDATE data_dict SET sort="${item.sort}" WHERE id='${item.id}'`
    )
  }
  ctx.body = {
    code: 200,
    msg: '操作成功！',
    data: null
  }
  // } else {
  // ctx.body = {
  //   code: 405,
  //   msg: '服务器内部错误！',
  //   data: null
  // }
  // }
})

// 字典数据拼接成树状结构
router.get('/api/v1/dict/types/page', async function (ctx) {
  const query = ctx.request.query
  // console.log(query)
  // 新增时检查name是否重复、code是否重复、parentCode是否存在
  const [rows] = await promisePool.query(`SELECT * FROM data_dict`)
  // console.log(rows)
  const dataList = buildTree(rows)
  const newList = dataList.slice(
    query.pageSize * (query.pageNum - 1),
    query.pageSize * query.pageNum
  )
  ctx.body = {
    code: 200,
    msg: '查询成功！',
    data: {
      list: newList,
      total: dataList.length
    }
  }
})

// 字典数据拼接成树状结构-查询所有的
router.get('/api/v1/dict/types/pages', async function (ctx) {
  // const query = ctx.request.query
  // console.log(query)
  // 新增时检查name是否重复、code是否重复、parentCode是否存在
  const [rows] = await promisePool.query(`SELECT * FROM data_dict`)
  // console.log(rows)
  const dataList = buildTree(rows)
  ctx.body = {
    code: 200,
    msg: '查询成功！',
    data: dataList
  }
})

// 查询单个字典数据
router.get('/api/v1/dict/types/:id/form', async function (ctx) {
  const params = ctx.request.params
  // console.log(params)
  const [rows] = await promisePool.query(
    `SELECT * FROM data_dict WHERE id=${params.id}`
  )
  // console.log(rows)
  ctx.body = {
    code: 200,
    msg: '查询成功！',
    data: rows[0]
  }
})

// 更新数据字典的信息
router.put('/api/v1/dict/types/:id', async function (ctx) {
  const params = ctx.request.params
  const body = ctx.request.body
  console.log(params, body)
  if (await updateBeforeInspect(body, ctx)) return
  // 先插入一条数据再排序
  await promisePool.execute(
    `UPDATE data_dict SET name="${body.name}",code="${body.code}",parentCode="${
      body.parentCode || ''
    }",status="${body.status}",sort="${body.sort}",remark="${
      body.remark || ''
    }" WHERE id='${body.id}'`
  )
  const [rowList] = await promisePool.query(`SELECT * FROM data_dict`)
  const dataList = getDataAndReSort(rowList, body.code, body.sort)
  // console.log('dataList', dataList)
  for (const item of dataList) {
    await promisePool.execute(
      `UPDATE data_dict SET sort="${item.sort}" WHERE id='${item.id}'`
    )
  }
  ctx.body = {
    code: 200,
    msg: '操作成功！',
    data: null
  }
})

// 删除单个或多个数据字典的信息
router.delete('/api/v1/dict/types/:id', async function (ctx) {
  const params = ctx.request.params
  // console.log(params)
  // 不能存在子字典数据
  const [rows] = await promisePool.query(
    `SELECT * FROM data_dict WHERE id IN (${params.id})`
  )
  const parentCodeArr = rows.map((item) => item.code)
  const [rows2] = await promisePool.query(
    `SELECT * FROM data_dict WHERE parentCode IN (${parentCodeArr.join(',')})`
  )
  if (rows2.length) {
    ctx.body = {
      code: 400,
      msg: '当前存在子字典数据，不能删除！',
      data: null
    }
    return
  }
  const [ResultSetHeader] = await promisePool.execute(
    `DELETE FROM data_dict WHERE id='${params.id}'`
  )
  console.log('ResultSetHeader=', ResultSetHeader)
  ctx.body = {
    code: 200,
    msg: '操作成功！',
    data: null
  }
})
